import logging
import os
from typing import List

import pytest
from playwright.sync_api import Playwright, sync_playwright

from get_project_path import project_path
from utils.logger import GetLogger
from utils.serch_chome_path import search_path

def pytest_collection_modifyitems(
        session: "Session", config: "Config", items: List["Item"]
) -> None:
    # item表示每个测试用例，解决用例名称中文显示问题
    for item in items:
        item.name = item.name.encode("utf-8").decode("unicode-escape")
        item._nodeid = item._nodeid.encode("utf-8").decode("unicode-escape")
# 配置日志
@pytest.fixture(scope="session", autouse=True)
def logger():
    worker_id = os.environ.get("PYTEST_XDIST_WORKER", "master")
    print(f"Worker ID: {worker_id}")  # 添加打印语句
    # log_file = os.path.join(project_path, "logs", f"webautotest_{worker_id}.log")
    logger = GetLogger.get_logger()
    GetLogger.logger.info('日志对象初始化成功')
    yield logger
    GetLogger.close_logger()
    GetLogger.logger.info('日志对象关闭成功')

@pytest.fixture(scope="function")
def setup(logger,playwright: Playwright):
    logger.info("启动浏览器并初始化页面")
    # with sync_playwright() as playwright:
    executable_path = search_path()
    browser = playwright.chromium.launch(
        headless=False,
        slow_mo=100,
        args=['--start-maximized'],
        executable_path=executable_path
    )
    # desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
    # file_path = os.path.join(desktop_path, 'auth.json')
    # with open(file_path, 'r', encoding='utf-8') as file:
    #     storage_state = json.load(file)
    # print(storage_state)
    context = browser.new_context(**playwright.devices['iPhone 11'])
    page = context.new_page()
    yield page
    logger.info("关闭浏览器")
    context.close()
    browser.close()